package com.muyaxuan.mail.controller.customer;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.muyaxuan.mail.common.EmailTool;
import com.muyaxuan.mail.dao.UserDao;
import com.muyaxuan.mail.dto.User;
@RequestMapping("/customer")
@Controller
public class UserControlller{
	/**
	 * 跳转注册页面
	 * @return
	 */
	@RequestMapping("/showMember")
	public String showMember(){
		
		return "member";
	}
	/**
	 * 跳转注册页面
	 * @return
	 */
	@RequestMapping("/showRegister")
	public String showRegister(){
		
		return "register";
	}
	/**
	 * 发送邮箱验证码
	 * @param address
	 * @param session
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/sendEmailCode")
    public Map<String,Object> sendEmailCode(String address,HttpSession session){
		//生产随机数对象
		Random random = new Random();
		
		Map<String,Object> map = new HashMap<>();
		
		StringBuilder emailCode = new StringBuilder();
		for(int i=0;i<4;i++){
			emailCode.append(random.nextInt(10));
		}
		
		String title="注册验证码";
		
		String content="您的沐雅轩账号注册验证码为:"+emailCode;
		//发送邮件
		boolean flag = EmailTool.send(address,title,content);
		
		if(flag){
			session.setAttribute("emailCode", emailCode.toString());
			
			map.put("tip", "请登录邮箱,查看验证码!"+emailCode.toString());
		}else{
			map.put("tip", "发送失败,注意检查邮箱是否正确!");
		}

		return map;
	}
	/**
	 * 用户注册
	 * @param user
	 * @param emailCode
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/register")
	public Map<String,Object> register(User user,String emailCode,HttpServletRequest request){
		HttpSession session = request.getSession();
		UserDao userDao = null;
		Map<String,Object> map = new HashMap<String,Object>();
		String vEmailCode = (String)session.getAttribute("emailCode");
	
		if(emailCode==null||!vEmailCode.equals(emailCode)){
			map.put("status", 1);
			map.put("tip", "验证码错误");
		}else{
			
			userDao = new UserDao();
			
			user.setCreateDate(new Date());
			
			String tip = userDao.insertUser(user);
			
			map.put("status", 0);
			map.put("tip", tip);
		}
		
	    return map;
	}
	
	
	
	
	
	

}
